<template>
  <div
    v-show="visible"
    :class="[
      'toolbar-select-option',
      {
        'is-selected': itemSelected,
        'is-disabled': isDisabled,
        'is-hover': hover,
      },
    ]"
    @mouseenter="handleMouseEnter"
    @mouseleave="handleMouseLeave"
    @click.stop="selectOptionClick"
  >
    <slot>
      <span>{{ currentLabel }}</span>
    </slot>
  </div>
</template>

<script setup lang="ts">
import { computed, inject, onBeforeUnmount, onMounted, ref } from "vue";
import { selectKey } from "./token";
import { useOption } from "./useOption";
import type { SelectOptionProxy } from "./types";

const props = defineProps<{
  value: any;
  label?: string;
  disabled?: boolean;
}>();

const select = inject(selectKey)!;
const hover = ref(false);

const {
  currentLabel,
  itemSelected,
  isDisabled,
  selectOptionClick,
  updateOption,
} = useOption(props);

const visible = computed(() => {
  const option = select.state.options.get(props.value);
  return option?.visible !== false;
});

const handleMouseEnter = () => {
  if (!isDisabled.value) {
    hover.value = true;
    const index = select.optionsArray.findIndex(
      (opt) => opt.value === props.value
    );
    if (index > -1) {
      select.state.hoveringIndex = index;
    }
  }
};

const handleMouseLeave = () => {
  hover.value = false;
};

// 创建选项 Proxy（使用 getter 实现响应式）
const optionProxy: SelectOptionProxy = {
  get value() {
    return props.value;
  },
  get label() {
    return props.label || String(props.value);
  },
  get currentLabel() {
    return currentLabel.value;
  },
  get disabled() {
    return props.disabled || false;
  },
  get visible() {
    return visible.value;
  },
  get hover() {
    return hover.value;
  },
  get itemSelected() {
    return itemSelected.value;
  },
  get isDisabled() {
    return isDisabled.value;
  },
  selectOptionClick,
  updateOption,
};

onMounted(() => {
  select.onOptionCreate(optionProxy);
});

onBeforeUnmount(() => {
  select.onOptionDestroy(props.value, optionProxy);
});
</script>

<style scoped lang="scss">
.toolbar-select-option {
  padding: 8px 12px;
  font-size: var(--editor-font-size);
  color: var(--editor-text-color);
  cursor: pointer;
  transition: background-color 0.2s;
}

.toolbar-select-option:hover:not(.is-disabled) {
  background-color: var(--editor-button-hover-background);
}

.toolbar-select-option.is-selected {
  color: var(--editor-primary-color);
  background-color: var(--editor-content-node-selected-background);
}

.toolbar-select-option.is-disabled {
  opacity: 0.5;
  cursor: not-allowed;
  color: var(--editor-text-color-disabled);
}

.toolbar-select-option.is-hover {
  background-color: var(--editor-button-hover-background);
}
</style>
